<template>
  <div>
    <el-card>
      <div class="coll_title">权限组管理</div>
      <el-button type="primary" @click="addRouteShow">添加权限组</el-button>
    </el-card>
    <el-card class="mag_t-20">
      <el-table :data="list" :border="true">
        <el-table-column type="selection" width="40" />
        <el-table-column prop="id" label="ID" width="50" />
        <el-table-column prop="rootName" label="权限组"/>
        <el-table-column label="操作" min-width="120">
          <template #default="scope">
            <el-button type="primary" @click="addData(scope.row,'预览')">查看</el-button>
            <el-button type="primary" @click="addData(scope.row,'编辑')">编辑</el-button>
            <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon-color="#626AEF"
                title="确定删除该权限组吗?"
                @confirm="deleteData(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="mag_t-20">
        <el-pagination
            v-model:current-page="page"
            v-model:page-size="limit"
            :page-sizes="[10, 20, 30, 40, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="count"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>

    </el-card>

    <el-dialog v-model="visible" :show-close="false" width="1100px">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <div class="wh_f">
            <div class="flex_1"><h4 :id="titleId" :class="titleClass">
              {{ title }}</h4></div>
            <div><el-button type="danger" @click="close">X</el-button></div>
          </div>
        </div>
      </template>
      <div>
        <div class="wh_f">
          <div class="flex_3">
            <titleText title="模块"></titleText>
            <div>
              <el-form ref="ruleFormRef" :model="form" label-width="auto"  :rules="rules">

                <el-form-item label="权限组：" prop="rootName">
                  <el-input :disabled="title=='预览'" v-model="form.rootName" style="width: 240px" placeholder="权限组名称" />
                </el-form-item>
                <el-form-item v-if="title!=='添加'" label="权限路由：" prop="rootList">
                  <el-cascader :disabled="title=='预览'" v-model="form.rootList" :options="rootlist" @change="handleChange" :props="{ multiple: true }" clearable />
                </el-form-item>
              </el-form>
              <div class="wz_rigdq">
                <el-button :disabled="isLook" @click="pushData(ruleFormRef)" type="primary" size="large">确 定</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
// 引用状态存储
import { storeVuex } from "@/store/modules/user";
import {storeToRefs} from "pinia";
const vuex = storeToRefs(storeVuex())
import {onMounted, reactive, ref} from "vue";
import {Adminroot, route} from "@/api";
import {ElMessage, type FormInstance} from "element-plus";
import root from "@/api/modules/root";
let list = ref()
let Classlist = ref()
const ruleFormRef = ref<FormInstance>() //验证规则
let rootView = ref(true)//分配权限组弹框
let visible = ref(false)
let form:any = reactive({})
let rootlist:any = ref([])//路由列表
let Root_form = reactive({})//权限组
let rules = reactive({
 rootName: [
    { required: true, message: '请输入权限组名称', trigger: 'blur' },
    { min: 1, max: 10, message: '请输入1-10位字符', trigger: 'blur' },
  ],
  rootList: [
    {
      required: true,
      message: '请选择权限组',
      trigger: 'change',
    }
  ],
})
//分页初始值
let page = ref(1)
let limit = ref(10)
let count = ref()
let title = ref('')
let isLook = ref(false)
onMounted(()=>{
  getList()
  //getAdminRoot_List()
  getClassList()
  getRoutePage_List()
})

//获取一二级路由页面数据
const getRoutePage_List = async ()=>{
  let res = await route.getRoutePage_List({})
  rootlist.value = res.data.data
}
let RouterRootlist = ref()
// 监听路由选择框
const handleChange = (e:any)=>{
  //权限路由选择器为空时 path也设为空 防止后端解析
  if(form.rootList){
    form.path = []
  }
  console.log('选择值',e)
  form.rootList = e
  // 防止重复push 每一项处理前需要先清空
  RouterRootlist.value = []
  e.forEach((item:any)=>{
    let itemList= rootlist.value.find((option:any)=>option.id === item[0])
    //确定找到匹配的id
    if(itemList){
      let childrenList:any = itemList.children.find((child:any)=>child.id === item[1])
      RouterRootlist.value.push(childrenList)
      form.path = RouterRootlist.value
    }
  })
}


// 获取用户权限路由列表
const getList = async ()=>{
  let res = await Adminroot.getAdminRoot_List({
    page:page.value,
    limit:limit.value,
  })
  console.log('数据',res.data.data)
  list.value = res.data.data
  count.value = res.data.data.count;
}


// 获取路由列表
// const getList = async ()=>{
//   let res = await route.getRouteList({
//     page:page.value,
//     limit:limit.value,
//   })
//   list.value = res.data.data.data
//   count.value = res.data.data.count;
// }
// 获取路由分类列表
const getClassList = async ()=>{
  let res = await route.getRoute_ClassList({})
  Classlist.value = res.data.data.data
}
// 查看/编辑列表
const addData = (e:any,tit:any)=>{
  // isLook.value = true
  //  form.rootList = JSON.parse(JSON.stringify(e.rootList))
  // alert(e.rootList)

    form.id=e.id
    /*如果rootList权限列表被清空 那么path设为空 后端就不会解析到错误的path添加到数据库*/
    if(form.rootList){
      form.path=e.children
    }else{
      form.path=[]
    }
    if(e.rootList){form.rootList= JSON.parse(e.rootList)}
    form.rootName=e.rootName

  visible.value = true
  title.value = tit
}
// 点击添加 打开弹窗
const addRouteShow = async(e:any)=>{
  visible.value=true
  isLook.value= false
  title.value='添加'
  Object.keys(form).forEach(key =>{
    // @ts-ignore
    form[key] = ''
  })
  // @ts-ignore
  form.is_show = 1
}
// 删除路由
const deleteData = async(e:any)=>{
  const res = await root.deleteAdminRoot({id:e})
  getList()
  ElMessage({
    // @ts-ignore
    message: res.data.msg,
      type: res.data.status==1?'success':'error'
  })
}
// 添加 修改路由
const pushData = async (e:any)=>{
    if (!e) return
    await e.validate(async (valid: any, fields: any) => {
      if (valid) {
        if (title.value == '添加') {
          const res = await root.addAdminRoot({
            rootName: form.rootName,
            route_id: form.route_id,
            rootList: JSON.stringify(form.rootList),
          })
          visible.value = false
          getList()
          ElMessage({
            // @ts-ignore
            message: res.data.msg,
            type: res.data.status == 1 ? 'success' : 'error'
          })
        } else {
          //编辑时运行
          form.rootList = JSON.stringify(form.rootList)
          form.path = JSON.stringify(form.path)
          const res = await root.updateAdminRoot({
            id: form.id,
            rootName: form.rootName,
            rootList: form.rootList,
            route_id: form.route_id,
            path: form.path
          })
          console.log('res', res)
          visible.value = false
          ElMessage({
            // @ts-ignore
            message: res.data.msg,
            type: res.data.status == 1 ? 'success' : 'error'
          })
          console.log(111, res.data)
          getList()

        }
      } else {
        console.log('不可以通过', fields)
      }
    })

}


// 分页
const handleSizeChange = async ()=>{
  getList();
}
const handleCurrentChange = async ()=>{
  getList();
}
</script>
<style scoped>

</style>
